import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *



def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)
    
    
    

def On_InputPage_UploadDetail_Picture_ByPictureNameListStr(driver:WebDriver,picture_name_list_str:str):
    """根据用户输入的图片名称列表字符串上传详情页图片

    Args:
        driver (WebDriver): driver 实例
        picture_name_list_str (str): 图片名称列表字符串
    """
    try:
        # 滚动到目标元素
        # element = driver.find_element(by=By.XPATH,value="//div[@id='detail_pic']//*[text()='本地上传']")
        # driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='快捷编辑']"))
        
        # 对 Input 控件进行有一个输入上传.
        element = driver.find_element(by=By.XPATH,value="//div[@id='detail_pic']//input[@type='file']")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        element.send_keys(picture_name_list_str)
    except (NoSuchElementException,TimeoutException):
        print_with_time(f"提示 : 没有找到主图上传图片的 [input] 控件元素!")
    finally:
        time.sleep(5)


def On_InputPage_UploadDetail_Picture_ByPictureNameList(driver:WebDriver,picture_name_list:list,Delay:float=5):
    """批量上传详情页图片

    Args:
        driver (WebDriver): driver 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print_with_time(picture_list_str)

    On_InputPage_UploadDetail_Picture_ByPictureNameListStr(driver=driver,picture_name_list_str=picture_list_str)
    

    # try:
    #     element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@id='detail_pic']//input[@type='file']")))
    #     driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='快捷编辑']"))
    #     element.send_keys(picture_list_str)
    # except (NoSuchElementException,TimeoutException):
    #     print(f"提示 : 没有找到详情图上传图片的 [input] 控件元素!")
    # finally:
    #     time.sleep(Delay)





def On_InputPage_UploadDetail_Picture_ByDirectory(driver:WebDriver,picture_directory_path:str,Delay:float=5):
    """批量上传详情页图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print_with_time(picture_list_str)


    On_InputPage_UploadDetail_Picture_ByPictureNameListStr(driver=driver,picture_name_list_str=picture_list_str)
    # try:
    #     element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@id='detail_pic']//input[@type='file']")))
    #     driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='快捷编辑']"))
    #     element.send_keys(picture_list_str)
    # except (NoSuchElementException,TimeoutException):
    #     print(f"提示 : 没有找到详情图上传图片的 [input] 控件元素!")
    # finally:
    #     time.sleep(Delay)